package com.module.lemlin.owner

import android.app.Application
import androidx.lifecycle.*
import com.blankj.utilcode.util.LogUtils
import com.module.lemlin.http.HttpResponseBody
import com.module.lemlin.http.SubscribeViewModel
import io.reactivex.rxjava3.disposables.CompositeDisposable
import kotlinx.coroutines.*
import kotlinx.coroutines.selects.whileSelect
import java.lang.Exception

open class OwnerViewModel(application: Application) : AndroidViewModel(application) {

    val dispose: CompositeDisposable = CompositeDisposable()

    public override fun onCleared() {
        if (dispose.size() > 0 && !dispose.isDisposed) {
            dispose.dispose()
        }
    }

    fun <data> setRxLifeScope(
        listener: SubscribeViewModel<data>, block: suspend CoroutineScope.() -> data
    ) {
        rxLifeScope.launch({
            listener.onSuccess(block())
        }, {
            listener.onFailure(it)
        }, {
            listener.onStart()
        })
    }

    fun <data> setViewModelScope(
        listener: SubscribeViewModel<data>, block: suspend CoroutineScope.() -> data
    ) {
        viewModelScope.launch {
            listener.onStart()
            try {
                listener.onSuccess(block())
            } catch (e: Throwable) {
                listener.onFailure(e)
            }
        }
    }
}
